#include "DeviceMgr.h"
#include "SimpleGeometry.h"

namespace DX
{
	DirectX::DirectX(WINDOW::WinDows& p_win) : m_wnd(p_win)
	{
		g_d3d = Direct3DCreate9(D3D_SDK_VERSION);

		D3DPRESENT_PARAMETERS params;
		memset(&params, 0, sizeof(params));
		params.BackBufferFormat = D3DFMT_X8R8G8B8;
		params.AutoDepthStencilFormat = D3DFMT_D24S8;
		if(!IsDepthFormatOk(params.AutoDepthStencilFormat, params.BackBufferFormat, params.BackBufferFormat))
		{
			MessageBoxA(m_wnd.GetHWND(), TEXT("Error: Some failure in the BackBuffer acursed."), NULL, MB_OK | MB_ICONERROR);
			ExitProcess(0);
		}
		params.BackBufferHeight = m_wnd.GetWindowSize().cy;
		params.BackBufferWidth = m_wnd.GetWindowSize().cx;
		params.EnableAutoDepthStencil = true;
		params.hDeviceWindow = m_wnd.GetHWND();
		params.SwapEffect = D3DSWAPEFFECT_DISCARD;
		params.Windowed = true;

		HRESULT hr = g_d3d->CreateDevice(0, D3DDEVTYPE_HAL, m_wnd.GetHWND(), D3DCREATE_HARDWARE_VERTEXPROCESSING, &params, &g_d3dDevice);
		if(FAILED(hr))
		{
			MessageBoxA(m_wnd.GetHWND(), DXGetErrorString(hr), NULL, MB_OK | MB_ICONERROR);
			ExitProcess(0);
		}

		//Start Init
		/*m_triangle = new Geometry::Triangle(100, 100, 200, 200);*/
		//End Init

		D3DXMATRIX matProj;
		D3DXMatrixPerspectiveFovLH(&matProj, D3DXToRadian(45.0f), (float)m_wnd.GetWindowSize().cx / m_wnd.GetWindowSize().cy, 1.0f, 10000.0f);
		g_d3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);

		D3DXMATRIX matView;
		D3DXVECTOR3 vEye(600.0f, 50.0f, 600.0f), vTarget(0.0f, 50.0f, 0.0f), vUp(0.0f, 1.0f, 0.0f);
		D3DXMatrixLookAtLH(&matView, &vEye, &vTarget, &vUp);
		g_d3dDevice->SetTransform(D3DTS_VIEW, &matView);

		g_d3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
		g_d3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);

	}

	void DirectX::Render()
	{
		g_d3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, D3DCOLOR_XRGB(127, 75, 37), 1.0f, 0);
		g_d3dDevice->BeginScene();

		g_d3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
		g_d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
		g_d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

		//Start Renders
		/*m_triangle->DrawTriangle(*this);*/
		
		//End Renders

		g_d3dDevice->EndScene();
		g_d3dDevice->Present(NULL, NULL, NULL, NULL);
	}
}